package cn.bgs.serviceedu.controller;


import cn.bgs.serviceedu.entity.Category;
import cn.bgs.serviceedu.service.CategoryService;
import cn.bgs.serviceedu.vo.RedisTop;
import cn.bgs.serviceutils.utils.CSException;
import cn.bgs.serviceutils.utils.R;
import cn.bgs.serviceutils.utils.RedisUtils;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 种类表 前端控制器
 * </p>
 *
 * @author YiChen
 * @since 2021-10-20
 */
@Api(description = "种类表")
@RestController
@RequestMapping("/serviceedu/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisUtils redisUtils;


    @ApiOperation(value = "分页模糊查询")
    @PostMapping("/findAll")
    @CachePut(key = "'CategoryList'",value = "CategoryList")
    public R findAll(@RequestBody(required = false) Category category){
        LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery()
                .like(StringUtils.isNoneBlank(category.getCategoryName()),Category::getCategoryName,StringUtils.trimToEmpty(category.getCategoryName()))
                .eq(Category::getDeleteFlag,0)
                .orderByAsc(Category::getCreateTime);
        return R.ok().data("list",categoryService.list(wrapper));
    }


    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID删除")
    @DeleteMapping("/del/{id}")
    @CachePut(key = "'CategoryList'",value = "CategoryList")
    public R del(@PathVariable Integer id){
        boolean b = categoryService.removeById(id);
        if (b){
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }


    /**
     * 根据ID单查
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID单查")
    @GetMapping("/findById/{id}")
    public R findById(@PathVariable Integer id){
        return   R.ok().data("list",categoryService.getById(id));
    }


    /**
     * 添加品种
     * @param category
     * @return
     */
    @ApiOperation(value = "添加品种")
    @PostMapping("/addCategory")
    @CachePut(key = "'CategoryList'",value = "CategoryList")
    public R addUser(@RequestBody Category category ){
        category.setBrowse(0);
        boolean save = false;
        try {
            save = categoryService.save(category);
        } catch (Exception e) {
            throw new CSException(20001,"添加失败");
        }
        if (save){
            return R.ok().message("添加成功");
        }
        return R.error().message("添加失败");
    }


    /**
     * 修改用户
     * @param category
     * @return
     */
    @ApiOperation(value = "修改品种")
    @PutMapping("/update")
    @CachePut(key = "'CategoryList'",value = "CategoryList")
    public R update(@RequestBody Category category){
        boolean update = false;
        try {
            update = categoryService.updateById(category);
        } catch (Exception e) {
            throw new CSException(20001,"修改失败");
        }
        if (update){
            return  R.ok().message("修改成功");
        }else{
            return R.error().message("修改失败");
        }
    }

    /**
     * 查询所有种类排行榜
     */
    @ApiOperation(value = "查询所有种类排行榜")
    @GetMapping("/top")
    @Cacheable(key = "'CategoryTop'",value = "CategoryTop")
    public R top(){
        List<Category> redisList = null;
        try {
            redisList = categoryService.getListTop();
        } catch (Exception e) {
            throw new CSException(20001,"排行榜查询失败");
        }
        return R.ok().data("list",redisList);
    }


    /**
     * 查看种类
     * @param id
     * @return
     */
    @ApiOperation(value = "查看种类")
    @GetMapping("/browse/{id}")
    public R browse(@PathVariable Long id){
        String key ="category:"+id;
        long incr = redisUtils.incr(key, 1);
        return R.ok().data("count",incr);
    }

    /**
     * 查询所有种类浏览
     */
    @ApiOperation(value = "查询所有种类浏览")
    @GetMapping("/look")
    public R look(){
        List<RedisTop> redisList = categoryService.getRedisList();
        return R.ok().data("list",redisList);
    }

    /**
     * 手动持久化数据
     * @return
     */
    @ApiOperation(value = "手动持久化数据")
    @GetMapping("/add")
    public R add(){
        List<RedisTop> redisTops = categoryService.getRedisList();
        Category category = new Category();
        try {
            for (int i = 0; i < redisTops.size(); i++) {
                RedisTop redisTop = redisTops.get(i);
                Category byId = categoryService.getById(redisTop.getId());
                if (!byId.getBrowse().equals(redisTop.getValue())) {
                    category.setId(Long.valueOf(redisTop.getId()));
                    category.setBrowse(redisTop.getValue());
                    categoryService.updateById(category);
                }
            }
        } catch (NumberFormatException e) {
            throw new CSException(20001,"数据修改失败");
        }
        return R.ok();
    }


    @GetMapping("/hello")
    public String hello() throws BlockException {

        return "hello";
    }

}
